package com.nami.dispatcher.application.grpmsg;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.nami.dispatcher.application.convertor.Cmd2GrpModelConvertor;
import com.nami.dispatcher.domain.gateway.UserGateway;
import com.nami.dispatcher.domain.model.NtfGrpReceiverModel;
import com.nami.dispatcher.domain.model.NtfSenderModel;
import com.nami.dispatcher.domain.service.DispatchCommonDomainService;
import com.nami.dispatcher.domain.service.DispatchGrpDomainService;
import com.nami.dispatcher.facade.grpmsg.ForwardGrpMsgFacade;
import com.nami.dispatcher.facade.grpmsg.request.command.GrpDispatchCmd;
import com.nami.gate.external.basic.bo.ConnectedUserBO;
import com.nami.gate.external.basic.cache.user.UserSessionRel;
import com.nami.gate.external.basic.cache.user.DeviceInfo;
import com.nami.im.network.model.message.v2.Message;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

import static com.nami.dispatcher.domain.manager.ThreadPoolManager.GDISPATCHERS;

@Slf4j
@Service
@RequiredArgsConstructor
public class ForwardGrpMsgFacadeImpl implements ForwardGrpMsgFacade {

    private final DispatchCommonDomainService commonDomainService;
    private final DispatchGrpDomainService grpDomainService;
    private final UserGateway userGateway;

    @Override
    public void execute(GrpDispatchCmd cmd) {
        GDISPATCHERS.execute(() -> {
            try {
                TimeInterval timer = DateUtil.timer();

                ConnectedUserBO sender = cmd.getSender();
                Message message = cmd.getMessage();
                if (!cmd.isSuccess()) {
                    commonDomainService.failResp(message,
                        sender.getSessionId(), sender.getConnectId(), cmd.getErrCode());
                    return;
                }
                log.info("[DISPATCHER-G] 群聊消息任务 ==> {}", message.getMsgId(), message.getMsgContent());
                commonDomainService.notifySender(buildSenderModel(cmd));

                Map<String, List<UserSessionRel>> onlineGrpClients = grpDomainService.findOnlineGrpClients(sender.getAppKey(),
                    cmd.getMemberUserIds());
                NtfGrpReceiverModel recvModel = Cmd2GrpModelConvertor.toReceiverTransModel(onlineGrpClients,
                    cmd);
                grpDomainService.notifyReceiver(recvModel);
                if (timer.interval() > 200) {
                    log.warn("[DISPATCHER-G] 群聊转发器出现处理慢 senderId={}, recvId={}, msgId={}, use={}ms",
                        sender.getUserId(), message.getTargetId(),
                        message.getMsgId(), timer.interval());
                }
            } catch (Exception var3) {
                var3.printStackTrace();
                log.error("[DISPATCHER-G] 消息下发出现错误：{}", var3);
            }

        });
    }

    private @NotNull NtfSenderModel buildSenderModel(GrpDispatchCmd cmd) {
        ConnectedUserBO sender = cmd.getSender();
        Message message = cmd.getMessage();
        // 获取from其他在线客户端
        List<DeviceInfo> senderOnlineDevices = userGateway.getOnlineDevicesExceptThisDevice(sender.getAppKey(),
            message.getSenderId(), sender.getInstanceId());

        NtfSenderModel model = new NtfSenderModel();
        model.setMessage(message);
        model.setTag(sender.getConnectId());
        model.setSessionId(sender.getSessionId());
        model.setOtherClients(senderOnlineDevices);
        model.setAppKey(sender.getAppKey());
        model.setQos(cmd.getQos());
        return model;
    }


}
